from wxauto import WeChat
import time
import os

def get_chat_history(contact_name):
    # 创建 WeChat 对象
    wx = WeChat()
    # 切换到指定联系人或群聊的聊天窗口
    wx.ChatWith(contact_name)
    time.sleep(2)  # 等待聊天窗口加载

    all_msg=[]
    # 获取当前聊天窗口的所有消息
    messages = wx.GetAllMessage()# 调用函数
    for message in messages:
        all_msg.append(f"{message[0]}:{message[1]}")
    path=os.getcwd()
    file_path = os.path.join(path, f"{contact_name}所有聊天记录.txt")
    with open(file_path,'w',encoding='utf-8') as f:
        for item in all_msg:
            f.write(item+'\n')

    return file_path

if __name__ == "__main__":
    # 替换为你要获取聊天记录的联系人或群聊名称
    contact_name = "不可一日无笑"
    file_path = get_chat_history(contact_name)
    print(file_path)